const db = uniCloud.database()
const dbCmd = db.command;
module.exports = {
	main: async (event) => {
		let {
			res,
			data,
			action
		} = event;
		switch (action) {
			case 'query':
				res.data = await getData(data);
				break;
			case 'queryById':
				res.data = await getDataById(data);
				break;
			case 'add':
				res = await addData(data);
				break;
			case 'edit':
				res = await editData(data);
				break;
			case 'del':
				res = await delData(data);
				break;
			default:
				res = {
					code: 402,
					msg: '非法访问'
				}
				break;
		}
		return res;
	}
}

/**
 * 获取列表数据
 */
async function getData(data) {
	var result = await db.collection('source').where({
			'groupId': data.groupId,
			'type': data.type
		})
		.skip(data.offset)
		.limit(10)
		.orderBy('updatetime', 'desc')
		.get()
	return result.data
}
/**
 * 获取数据通过ID
 */
async function getDataById(data) {
	var result = await db.collection('selfget').doc(data._id).get();
	return result.data
}
/**
 * 添加数据
 */
async function addData(data) {
	var res = {}
	const result2 = await db.collection('source').add({
		type: data.type,
		url: data.url,
		height: data.height,
		groupId: data.groupId,
		updatetime: data.updatetime
	})

	var result = await db.collection('source').where({
			'url': data.url
		})
		.orderBy('updatetime', 'desc')
		.get()
	res.code = 200;
	res.data = result.data
	return res;
}
/**
 * 更新数据
 */
async function editData(data) {
	var res = {}
	const result = await db.collection('source').doc(data.id).update({
		groupId: data.groupId,
		updatetime: data.updatetime
	})
	res.code = 200;
	res.data = result.data
	return res;
}
/**
 * @param {Object} data
 * 删除数据
 */
async function delData(data) {
	var res = {}
	var tmp = await db.collection('source').doc(data.id).remove()
	if (tmp.deleted === 1) {
		let result = await uniCloud.deleteFile({
		    fileList: [
		        data.url
		    ]
		});
		res.code = 200
		res.msg = '删除成功'
	} else {
		res.code = 402
		res.msg = '删除失败'
	}
	return res
}
